package com.lifeverse.controller;

import com.lifeverse.common.ApiResponse;
import com.lifeverse.entity.BehaviorPattern;
import com.lifeverse.entity.PatternAlert;
import com.lifeverse.repository.BehaviorPatternRepository;
import com.lifeverse.repository.PatternAlertRepository;
import com.lifeverse.service.PatternRecognitionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 模式识别控制器
 * 提供模式识别相关的API接口
 */
@RestController
@RequestMapping("/api/pattern-recognition")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "模式识别", description = "生命体行为模式识别和分析API")
public class PatternRecognitionController {

    private final PatternRecognitionService patternRecognitionService;
    private final BehaviorPatternRepository behaviorPatternRepository;
    private final PatternAlertRepository patternAlertRepository;

    /**
     * 执行模式识别分析
     */
    @PostMapping("/analyze/{lifeEntityId}")
    @Operation(summary = "执行模式识别分析", description = "为指定生命体执行完整的模式识别分析")
    public ResponseEntity<ApiResponse<CompletableFuture<PatternRecognitionService.PatternRecognitionResult>>> analyzePatterns(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "行为数据") @RequestBody Map<String, Object> behaviorData) {
        
        log.info("收到模式识别分析请求，生命体ID: {}", lifeEntityId);
        
        try {
            CompletableFuture<PatternRecognitionService.PatternRecognitionResult> result = 
                    patternRecognitionService.performCompletePatternAnalysis(lifeEntityId, behaviorData);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("模式识别分析失败", e);
            return ResponseEntity.ok(ApiResponse.error("模式识别分析失败: " + e.getMessage()));
        }
    }

    /**
     * 批量执行模式识别
     */
    @PostMapping("/batch-analyze")
    @Operation(summary = "批量模式识别", description = "为多个生命体批量执行模式识别分析")
    public ResponseEntity<ApiResponse<CompletableFuture<PatternRecognitionService.BatchPatternRecognitionResult>>> batchAnalyzePatterns(
            @Parameter(description = "生命体ID列表") @RequestBody List<Long> lifeEntityIds) {
        
        log.info("收到批量模式识别请求，生命体数量: {}", lifeEntityIds.size());
        
        try {
            CompletableFuture<PatternRecognitionService.BatchPatternRecognitionResult> result = 
                    patternRecognitionService.performBatchPatternAnalysis(lifeEntityIds);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("批量模式识别失败", e);
            return ResponseEntity.ok(ApiResponse.error("批量模式识别失败: " + e.getMessage()));
        }
    }

    /**
     * 获取生命体的行为模式
     */
    @GetMapping("/patterns/{lifeEntityId}")
    @Operation(summary = "获取行为模式", description = "获取指定生命体的行为模式列表")
    public ResponseEntity<ApiResponse<Page<BehaviorPattern>>> getPatterns(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "lastDetectedAt") String sortBy,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "desc") String sortDir) {
        
        try {
            Sort.Direction direction = sortDir.equalsIgnoreCase("desc") ? Sort.Direction.DESC : Sort.Direction.ASC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortBy));
            
            Page<BehaviorPattern> patterns = behaviorPatternRepository.findByLifeEntityId(lifeEntityId, pageable);
            
            return ResponseEntity.ok(ApiResponse.success(patterns));
            
        } catch (Exception e) {
            log.error("获取行为模式失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取行为模式失败: " + e.getMessage()));
        }
    }

    /**
     * 获取模式预警
     */
    @GetMapping("/alerts/{lifeEntityId}")
    @Operation(summary = "获取模式预警", description = "获取指定生命体的模式预警列表")
    public ResponseEntity<ApiResponse<Page<PatternAlert>>> getPatternAlerts(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "triggeredAt"));
            Page<PatternAlert> alerts = patternAlertRepository.findByLifeEntityId(lifeEntityId, pageable);
            
            return ResponseEntity.ok(ApiResponse.success(alerts));
            
        } catch (Exception e) {
            log.error("获取模式预警失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取模式预警失败: " + e.getMessage()));
        }
    }

    /**
     * 获取未解决的预警
     */
    @GetMapping("/alerts/unresolved")
    @Operation(summary = "获取未解决预警", description = "获取所有未解决的模式预警")
    public ResponseEntity<ApiResponse<List<PatternAlert>>> getUnresolvedAlerts() {
        
        try {
            List<PatternAlert> alerts = patternAlertRepository.findUnresolvedAlerts();
            return ResponseEntity.ok(ApiResponse.success(alerts));
            
        } catch (Exception e) {
            log.error("获取未解决预警失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取未解决预警失败: " + e.getMessage()));
        }
    }

    /**
     * 获取高优先级预警
     */
    @GetMapping("/alerts/high-priority")
    @Operation(summary = "获取高优先级预警", description = "获取所有高优先级的模式预警")
    public ResponseEntity<ApiResponse<List<PatternAlert>>> getHighPriorityAlerts() {
        
        try {
            List<PatternAlert> alerts = patternAlertRepository.findHighPriorityAlerts();
            return ResponseEntity.ok(ApiResponse.success(alerts));
            
        } catch (Exception e) {
            log.error("获取高优先级预警失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取高优先级预警失败: " + e.getMessage()));
        }
    }

    /**
     * 确认预警
     */
    @PutMapping("/alerts/{alertId}/acknowledge")
    @Operation(summary = "确认预警", description = "确认指定的模式预警")
    public ResponseEntity<ApiResponse<PatternAlert>> acknowledgeAlert(
            @Parameter(description = "预警ID") @PathVariable Long alertId) {
        
        try {
            PatternAlert alert = patternAlertRepository.findById(alertId)
                    .orElseThrow(() -> new RuntimeException("预警不存在"));
            
            alert.setStatus(com.lifeverse.entity.enums.AlertStatus.ACKNOWLEDGED);
            alert.setAcknowledgedAt(java.time.LocalDateTime.now());
            
            PatternAlert savedAlert = patternAlertRepository.save(alert);
            
            return ResponseEntity.ok(ApiResponse.success(savedAlert));
            
        } catch (Exception e) {
            log.error("确认预警失败", e);
            return ResponseEntity.ok(ApiResponse.error("确认预警失败: " + e.getMessage()));
        }
    }

    /**
     * 解决预警
     */
    @PutMapping("/alerts/{alertId}/resolve")
    @Operation(summary = "解决预警", description = "解决指定的模式预警")
    public ResponseEntity<ApiResponse<PatternAlert>> resolveAlert(
            @Parameter(description = "预警ID") @PathVariable Long alertId) {
        
        try {
            PatternAlert alert = patternAlertRepository.findById(alertId)
                    .orElseThrow(() -> new RuntimeException("预警不存在"));
            
            alert.setStatus(com.lifeverse.entity.enums.AlertStatus.RESOLVED);
            alert.setResolvedAt(java.time.LocalDateTime.now());
            
            PatternAlert savedAlert = patternAlertRepository.save(alert);
            
            return ResponseEntity.ok(ApiResponse.success(savedAlert));
            
        } catch (Exception e) {
            log.error("解决预警失败", e);
            return ResponseEntity.ok(ApiResponse.error("解决预警失败: " + e.getMessage()));
        }
    }

    /**
     * 获取模式识别统计
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取统计信息", description = "获取模式识别的统计信息")
    public ResponseEntity<ApiResponse<PatternRecognitionService.PatternRecognitionStatistics>> getStatistics() {
        
        try {
            PatternRecognitionService.PatternRecognitionStatistics statistics = 
                    patternRecognitionService.getPatternRecognitionStatistics();
            
            return ResponseEntity.ok(ApiResponse.success(statistics));
            
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }

    /**
     * 生成模式识别报告
     */
    @GetMapping("/report/{lifeEntityId}")
    @Operation(summary = "生成模式报告", description = "为指定生命体生成模式识别报告")
    public ResponseEntity<ApiResponse<PatternRecognitionService.PatternRecognitionReport>> generateReport(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        
        try {
            PatternRecognitionService.PatternRecognitionReport report = 
                    patternRecognitionService.generatePatternReport(lifeEntityId);
            
            return ResponseEntity.ok(ApiResponse.success(report));
            
        } catch (Exception e) {
            log.error("生成模式报告失败", e);
            return ResponseEntity.ok(ApiResponse.error("生成模式报告失败: " + e.getMessage()));
        }
    }

    /**
     * 获取异常模式
     */
    @GetMapping("/patterns/anomalous")
    @Operation(summary = "获取异常模式", description = "获取所有异常的行为模式")
    public ResponseEntity<ApiResponse<List<BehaviorPattern>>> getAnomalousPatterns(
            @Parameter(description = "异常阈值") @RequestParam(defaultValue = "0.7") Double threshold) {
        
        try {
            List<BehaviorPattern> patterns = behaviorPatternRepository.findAnomalousPatterns(threshold);
            return ResponseEntity.ok(ApiResponse.success(patterns));
            
        } catch (Exception e) {
            log.error("获取异常模式失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取异常模式失败: " + e.getMessage()));
        }
    }

    /**
     * 获取高频模式
     */
    @GetMapping("/patterns/high-frequency")
    @Operation(summary = "获取高频模式", description = "获取所有高频的行为模式")
    public ResponseEntity<ApiResponse<List<BehaviorPattern>>> getHighFrequencyPatterns(
            @Parameter(description = "频率阈值") @RequestParam(defaultValue = "10") Integer minFrequency) {
        
        try {
            List<BehaviorPattern> patterns = behaviorPatternRepository.findHighFrequencyPatterns(minFrequency);
            return ResponseEntity.ok(ApiResponse.success(patterns));
            
        } catch (Exception e) {
            log.error("获取高频模式失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取高频模式失败: " + e.getMessage()));
        }
    }

    /**
     * 获取模式详情
     */
    @GetMapping("/patterns/detail/{patternId}")
    @Operation(summary = "获取模式详情", description = "获取指定行为模式的详细信息")
    public ResponseEntity<ApiResponse<BehaviorPattern>> getPatternDetail(
            @Parameter(description = "模式ID") @PathVariable Long patternId) {
        
        try {
            BehaviorPattern pattern = behaviorPatternRepository.findById(patternId)
                    .orElseThrow(() -> new RuntimeException("模式不存在"));
            
            return ResponseEntity.ok(ApiResponse.success(pattern));
            
        } catch (Exception e) {
            log.error("获取模式详情失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取模式详情失败: " + e.getMessage()));
        }
    }

    /**
     * 删除过期模式
     */
    @DeleteMapping("/patterns/expired")
    @Operation(summary = "清理过期模式", description = "删除所有过期的行为模式")
    public ResponseEntity<ApiResponse<String>> cleanupExpiredPatterns() {
        
        try {
            java.time.LocalDateTime expiredBefore = java.time.LocalDateTime.now().minus(30, java.time.temporal.ChronoUnit.DAYS);
            List<BehaviorPattern> expiredPatterns = behaviorPatternRepository.findExpiredPatterns(expiredBefore);
            
            behaviorPatternRepository.deleteAll(expiredPatterns);
            
            return ResponseEntity.ok(ApiResponse.success("已清理 " + expiredPatterns.size() + " 个过期模式"));
            
        } catch (Exception e) {
            log.error("清理过期模式失败", e);
            return ResponseEntity.ok(ApiResponse.error("清理过期模式失败: " + e.getMessage()));
        }
    }
}